package com.example.wn.message.service;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.example.wn.common.entity.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class MessageServiceImpl implements MessageService {

    @Autowired
    private RedisService redisService;

    @Override
    public void sendMessage(UserInfo userInfo) {
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", "LTAI4G1iRUa3GrGxahGcf5Uo", "g9QXIe1d10gp3pQY8ooYcn6GUoj1qY");
        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("dysmsapi.aliyuncs.com");
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");
        request.putQueryParameter("RegionId", "cn-hangzhou");

        String phone = userInfo.getPhone();
        request.putQueryParameter("PhoneNumbers", phone);
        request.putQueryParameter("SignName", "源码教室");
        request.putQueryParameter("TemplateCode", "SMS_192195638");

        //生成4位随机数
        int code = (int)((Math.random()*9+1)*1000);

        request.putQueryParameter("TemplateParam", "{\"code\":\""+code+"\"}");
        try {
            CommonResponse response = client.getCommonResponse(request);

            System.out.println(response.getData());
            if(response.getData().contains("OK")){



                System.out.println("短信发送成功");


                //将手机号和验证码存入Redis,并设置过期时间180s
                redisService.set(phone,code+"",180L);
            }

        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        }



    }
}
